package com.qijia.travel.app;

import org.apache.commons.fileupload.ProgressListener;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.ScriptProxy;

import com.qijia.travel.vo.ProgressInfo;

public class UploadListener implements ProgressListener {
	private static final long UPDATE_THRESHOLD = 50 * 1024L; // 

	private static WebContext wctx = null;
	
	private String functionCall = "updateProgress";

	@SuppressWarnings("deprecation")
	private ScriptProxy sp = null;

	private long megaBytes = -1;

	private ProgressInfo pi = null;

	public UploadListener() {
		wctx = WebContextFactory.get();
	}

	public UploadListener(ProgressInfo pi) {
		this.pi = pi;
	}

	@SuppressWarnings("deprecation")
	public void update(long pBytesRead, long pContentLength, int pItems) {

		try {
			// Make the upload more slowly, so we can see the progress bar for small file.
			// In Prod env. it should be removed.
			Thread.sleep(10);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		if(pBytesRead + 2000 > pContentLength){
			pi.setBytesRead(pContentLength);
			sp.addFunctionCall("updateProgress", pi);
			return;
		}
		long mBytes = pBytesRead / UPDATE_THRESHOLD;
		if (megaBytes == mBytes && megaBytes > 0) {
			return;
		}
		
		megaBytes = mBytes;
		pi.setBytesRead(pBytesRead);
		pi.setFileIndex(pItems);
		pi.setTotalSize(pContentLength);

		// WebContext wctx = WebContextFactory.get();
		// org.directwebremoting.proxy.dwr.Util utilThis = new
		// org.directwebremoting.proxy.dwr.Util(wctx.getScriptSession());
		// utilThis.setValue("text", String.valueOf(pBytesRead));
		if(sp == null){
			sp = new ScriptProxy(wctx.getScriptSessionsByPage(wctx.getCurrentPage()));
		}
		sp.addFunctionCall(getFunctionCall(), pi);

	}

	public void go() {
		System.out.println("---------go!");
	}

	public String getFunctionCall() {
		return functionCall;
	}

	public void setFunctionCall(String functionCall) {
		this.functionCall = functionCall;
	}
}
